﻿//using AppSocketControl.Relay;
//using AppSocketModel;
using AppSocketModel;
using BCGPSCommon; 
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace BCGPS.DataReceive.Service
{
    public class UDPHandle: SocketHandle
    {
        private IPEndPoint ipLocalPoint;
        private IPEndPoint RemotePoint;
        private UdpClient udpClient;
        private readonly IRedisService redisService;

        private bool RunningFlag = false; 

        public UDPHandle()
        {
           redisService = new RedisService();
        }

        public void Init(string ipAddress, string prot)
        {
            Console.WriteLine("in UDPHandle.Init() at 1");
            //得到本机IP，设置UDP端口号     
            IPAddress ip = GetValidIP(ipAddress);
            int port = GetValidPort(prot);
            ipLocalPoint = new IPEndPoint(ip, port);

            //定义网络类型，数据连接类型和网络协议UDP  
            udpClient = new UdpClient(ipLocalPoint);

            //启动一个新的线程，执行方法this.ReceiveHandle，  
            //以便在一个独立的进程中执行数据接收的操作 

            Console.WriteLine("in UDPHandle.Init()  at 2");
            RunningFlag = true;
            Thread thread = new Thread(new ThreadStart(this.ReceiveHandle));
            thread.Start(); 
        }

        #region 处理线程
        //定义一个委托  
        public delegate void MyInvoke(string strRecv);
        private void ReceiveHandle()
        {
            Console.WriteLine("in ReceiveHandle head  -- thread head");
            RemotePoint = new IPEndPoint(IPAddress.Any, 0);
            //接收数据处理线程
             
            while (RunningFlag)
            {
                try
                {
                    byte[] bytRecv = udpClient.Receive(ref RemotePoint);
                    string message = Encoding.ASCII.GetString(bytRecv, 0, bytRecv.Length);
                    message += "$" + RemotePoint.Address + "$"+RemotePoint.Port+"$"+ DateTime.Now.ToString("yyyy:MM:dd:HH:mm:ss:fff");
                    Console.WriteLine( "UDP-Rcv: "+ message );


                    //要处理的数据加入队列 
                    KafakaProducer.SendMsg(message); 

                    string[] arr = message.TrimStart('$').Split('$');
                    //命令下发
                    if (arr.Length >= 9)
                    {
                        if (redisService.Exists(GeneralContainer.RedisNameSpaceIMEISendCmd + arr[5]))
                        {
                            if (arr[6] == GpsFrame.LOCATION.ToString() || arr[6] == GpsFrame.LOCATIONLBS.ToString() || arr[6] == GpsFrame.LOCATIONLBSREAL.ToString() || arr[6] == GpsFrame.LOCATIONREAL.ToString())
                            {
                                string sendStr = redisService.Get<string>(GeneralContainer.RedisNameSpaceIMEISendCmd + arr[5]);
                                if (!string.IsNullOrWhiteSpace(sendStr))
                                {
                                    byte[] byteSend = System.Text.Encoding.UTF8.GetBytes(sendStr);
                                    udpClient.Send(byteSend, byteSend.Length, RemotePoint);
                                    Console.WriteLine("Send To : " + RemotePoint + "    " + sendStr + "               >>>>>>>>>>>>>>>>>  imei:=" + GeneralContainer.RedisNameSpaceIMEISendCmd + arr[5] + "  --------    GpsFrame:=" + arr[6]);
                                }
                            }
                        }
                    }

                    //转发
                    //if (arr.Length >= 9)
                    //{
                    //    if (RelayUdpClient.dict.ContainsKey(arr[5]))
                    //    {
                    //        var companyid = RelayUdpClient.dict[arr[5]];
                    //        if(RelayServer.GetRelayServer().relayClientDict.ContainsKey(companyid))
                    //        {
                    //            RelayServer.GetRelayServer().relayClientDict[companyid].relayQueue.Enqueue(message);
                    //        }

                    //    }
                    //}

                    // this.gpsDataService.Split(message);

                    //if (long.TryParse(message, out long userId))
                    //{
                    //this.messageHandle.HeartbeatProcess(userId, RemotePoint, udpClient);
                    //}
                    //else
                    //{
                    //    this.messageHandle.Process(message, RemotePoint, udpClient);
                    //}

                }
                catch (Exception ex)
                {
                    UpdateMsgTextBox("错误：" + ex.Message);
                }

            }
            udpClient.Close();
        }
        //public void btSend_Click(string msg)
        //{
        //    //msg = tbSendMsg.Text;
        //    //发送UDP数据包  
        //    byte[] data = Encoding.Default.GetBytes(msg);
        //    udpClient.Send(data, data.Length, RemotePoint);
        //}
        private void UpdateMsgTextBox(string msg)
        {
            //接收数据显示  
            Console.WriteLine(msg);
        }
        #endregion


        
        
    }
}
